﻿using System;
using System.Collections.Generic;
using System.Linq;

using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading;

namespace SecureRemoteControlServer
{
    class Bemfa
    {
        //巴法云服务器地址默认即可
        const string TcpServerAddress = "bemfa.com";

        //服务器端口
        //TCP创客云端口8344
        //TCP设备云端口8340
        const Int16 TcpServerPort = 8344;

        //最大字节数
        const int MaxPacketSize = 512;

        //设置心跳值30s
        const int KeepAliveTime = 30 * 1000;

        public delegate void ReceiveCallback(string message);

        #region Bemfa
        Socket BemfaSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        byte[] BemfaBuffer = new byte[MaxPacketSize];
        public void Connect(object receive)
        {
            bool Subscribed = false;
            new Thread(BemfaPing) { IsBackground = true }.Start();
            while (true)
            {
                if (!BemfaSocket.Connected)
                {
                    BemfaSocket.Connect(new IPEndPoint(Dns.GetHostAddresses(TcpServerAddress)[0], TcpServerPort));
                }
                if (BemfaSocket.Connected && !Subscribed)
                {
                    BemfaSocket.Send(System.Text.Encoding.Default.GetBytes("cmd=1&uid=" + Properties.Settings.Default.BemfaUid + "&topic=" + Properties.Settings.Default.BemfaTopic + "\r\n"));
                    var buffer = System.Text.Encoding.Default.GetString(BemfaBuffer, 0, BemfaSocket.Receive(BemfaBuffer));
                    Console.WriteLine(buffer);
                    if (buffer.Contains("res=1"))
                        Subscribed = true;
                    else
                        Subscribed = false;
                }
                if (BemfaSocket.Connected && Subscribed)
                {
                    var buffer = System.Text.Encoding.Default.GetString(BemfaBuffer, 0, BemfaSocket.Receive(BemfaBuffer));
                    Console.WriteLine(buffer);
                    ((ReceiveCallback)receive)(buffer);
                }
            }
        }

        private void BemfaPing()
        {
            while (true)
            {
                if(BemfaSocket.Connected)
                {
                    BemfaSocket.Send(System.Text.Encoding.Default.GetBytes("ping\r\n"));
                }
                Thread.Sleep(KeepAliveTime);
            }
        }
        #endregion
    }
}
